import React, { useEffect, useState, useCallback } from 'react';
import useFetchData from '@/hooks/getList';
import {
  Card,
  Table,
  TableColumnProps,
  Space,
  Button,
  Message,
  Popconfirm,
  Typography,
} from '@arco-design/web-react';
import {
  getRelationAccountPage,
  resetEnterpriseAccountPwd,
  updateEnterpriseAccountPassword,
  changeUserFrozenStatus,
} from '@/api/userData';
import styles from './style/index.module.less';
import ChildPwdForm from '@/pages/userManagement/accountList/childPwdForm';
import EditForm from '@/pages/userManagement/accountList/editForm';

const Text = Typography.Text;

function AccountList() {
  const { data, pagination, loading, getData } = useFetchData(
    getRelationAccountPage,
    {}
  );

  const [enterpriseCode, setEnterpriseCode] = useState('');

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'Date',
      align: 'center',
      render: (col, record: any, index: number) => index + 1,
    },
    {
      title: '校园账号',
      dataIndex: 'CTLAccount',
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'Alias',
      align: 'center',
    },
    {
      title: '用户昵称',
      dataIndex: 'CTLUserName',
      align: 'center',
    },
    {
      title: '账号状态',
      dataIndex: 'IsFrozen',
      align: 'center',
      render: (col, record: any, index: number) => {
        return col ? (
          <Text type="error">冻结</Text>
        ) : (
          <Text type="success">正常</Text>
        );
      },
    },
    {
      title: '身份',
      dataIndex: 'EnterpriseUserType',
      align: 'center',
      render: (col, record: any, index: number) => {
        return col === 3 ? '管理员' : col === 2 ? '教师' : '学生';
      },
    },
    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      fixed: 'right',
      width: 350,
      render: (_, record) => (
        <div>
          <Button
            type="text"
            onClick={() => {
              handlePwd(record, 'update');
            }}
          >
            修改登录密码
          </Button>
          <Button
            type="text"
            disabled={record.IsMaster}
            onClick={() => {
              handleEdit(record);
            }}
          >
            修改
          </Button>

          <Button
            type="text"
            status={record.IsFrozen ? 'success' : 'danger'}
            disabled={record.IsMaster || frozening}
            onClick={() => {
              handleFrozenStatus(record);
            }}
          >
            {record.IsFrozen ? <span>解冻</span> : <span>冻结</span>}
          </Button>
        </div>
      ),
    },
  ];

  /**
   * 修改密码
   */

  const updateFormList = [
    {
      field: 'newPassword',
      label: '新登录密码',
      rules: [{ required: true, message: '请输入新登录密码' }],
    },
    {
      field: 'againPassword',
      label: '确认登录密码',
      rules: [{ required: true, message: '请再次输入登录密码' }],
    },
  ];

  const [formList, setFormList] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [currentEditId, setCurrentEditId] = useState('');
  const handleChangeVisible = useCallback((visible) => {
    setModalVisible(visible);
  }, []);

  const handlePwd = useCallback((data, type) => {
    setModalTitle('修改登录密码');
    setFormList(updateFormList);
    setCurrentEditId(data.CTLUserId);
    setModalVisible(true);
  }, []);

  const onConfirm = useCallback(
    async (data) => {
      let res: any;
      res = await updateEnterpriseAccountPassword({
        CTLUserId: currentEditId,
        AccountPassword: data.newPassword,
      });

      if (res.StatusCode === 200) {
        Message.success(res.Message);
      } else {
        Message.error(res.Message);
      }
    },
    [currentEditId]
  );

  /**
   * 重置初始密码
   */

  const [tableSelectRows, settableSelectRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const resetEnterprisePwd = useCallback(async () => {
    if (tableSelectRows.length === 0) {
      Message.error({
        content: '请选择需要重置初始密码的校园账号',
      });
      return;
    }

    const reqData = tableSelectRows.map((item: any) => {
      return {
        CTLUserId: item.CTLUserId,
        IsMaster: item.IsMaster,
      };
    });

    const res: any = await resetEnterpriseAccountPwd({
      ResetAccountPasswordParams: reqData,
    });

    if (res.StatusCode === 200) {
      Message.success(res.Message);
      settableSelectRows([]);
      setSelectedRowKeys([]);
    } else {
      Message.error(res.Message);
    }
  }, [tableSelectRows]);

  const onChangeTable = useCallback((pagination) => {
    const { current, pageSize } = pagination;
    const obj = {
      PageIndex: current,
      PageSize: pageSize,
    };
    getData(obj);
  }, []);

  useEffect(() => {
    getData();
    const enterpriseCode = window.localStorage.getItem('enterpriseCode')
      ? window.localStorage.getItem('enterpriseCode')
      : '';
    setEnterpriseCode(enterpriseCode);
  }, []);

  /**
   * 修改
   */

  const [editVisible, setEditVisible] = useState(false);
  const [editData, setEditData] = useState({});
  const changeEditVisible = useCallback((visible) => {
    setEditVisible(visible);
  }, []);

  const handleEdit = useCallback((data) => {
    const editData = {
      CTLUserId: data.CTLUserId, //C端用户Id
      CTLUserName: data.CTLUserName, //用户名
      CTLAccount: data.CTLAccount, //账号名
      Alias: data.Alias, //学生名
    };
    setEditData(editData);
    setEditVisible(true);
  }, []);

  const onEditConfirm = async () => {
    getData();
  };

  // 解冻/冻结
  const [frozening, setFrozening] = useState(false);
  const handleFrozenStatus = async (row: any) => {
    setFrozening(true);
    const res: any = await changeUserFrozenStatus({
      CTLUserId: row.CTLUserId, //C端用户Id
      IsFrozen: !row.IsFrozen, //是否冻结
    });

    if (res.StatusCode === 200) {
      setTimeout(() => {
        getData();
        setFrozening(false);
      }, 1000);
      Message.success(res.Message);
    } else {
      setFrozening(false);
      Message.error(res.Message);
    }
  };

  return (
    <div>
      <SearchTable
        tableSelectRows={tableSelectRows}
        resetEnterprisePwd={resetEnterprisePwd}
        enterpriseCode={enterpriseCode}
      />
      <Card>
        <Table
          border
          borderCell
          scroll={{
            y: 570,
          }}
          rowSelection={{
            preserveSelectedRowKeys: true,
            checkCrossPage: true,
            type: 'radio',
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              settableSelectRows(selectedRows);
              setSelectedRowKeys(selectedRowKeys);
            },
          }}
          columns={columns}
          pagination={pagination}
          data={data}
          loading={loading}
          onChange={onChangeTable}
          rowKey="CTLUserId"
        />
      </Card>

      <ChildPwdForm
        visible={modalVisible}
        modalTitle={modalTitle}
        changeVisible={handleChangeVisible}
        onConfirm={onConfirm}
        formList={formList}
      ></ChildPwdForm>

      <EditForm
        visible={editVisible}
        modalTitle="修改账号信息"
        changeVisible={changeEditVisible}
        onConfirm={onEditConfirm}
        editData={editData}
      ></EditForm>
    </div>
  );
}

function SearchTable(props) {
  const { resetEnterprisePwd, enterpriseCode } = props;
  return (
    <Card className={styles.box}>
      <Space size="large">
        <Popconfirm
          position="bottom"
          focusLock
          title="提示"
          content="是否确认重置初始密码？"
          onOk={async () => {
            resetEnterprisePwd();
          }}
        >
          <Button>重置初始密码</Button>
        </Popconfirm>
        {!!enterpriseCode && <div>组织代码：{enterpriseCode}</div>}
      </Space>
    </Card>
  );
}

export default AccountList;
